<template>
  <div class="remind-page">
    <form @submit.prevent="onSubmit">
      <div class="section">
        <div class="section-title">用量信息设置</div>
        <div class="form-group">
          <div class="label">药品名</div>
          <input class="input" v-model="form.medname" :class="{'invalid': invalidFields.includes('medname')}" placeholder="请输入药品名" />
        </div>
        <div class="row">
          <div class="col">
            <div class="label">用药开始时间</div>
            <div class="value green" :class="{'invalid': invalidFields.includes('dtstatr')}" @click="openPicker('dtstatr')">{{ form.dtstatr || '请选择' }}</div>
          </div>
          <div class="col">
            <div class="label">用药结束时间</div>
            <div class="value green" :class="{'invalid': invalidFields.includes('dtend')}" @click="openPicker('dtend')">{{ form.dtend || '请选择' }}</div>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <div class="label">剂量单位</div>
            <input class="input" v-model="form.dose" :class="{'invalid': invalidFields.includes('dose')}" placeholder="请输入单位，如片/粒/ml/g" />
          </div>
          <div class="col">
            <div class="label">剂量数值</div>
            <input class="input" v-model="form.units" :class="{'invalid': invalidFields.includes('units')}" type="number" min="1" placeholder="请输入剂量" />
          </div>
        </div>
      </div>
      <div class="section">
        <div class="section-title">重复提醒设置</div>
        <div class="row">
          <div class="col">
            <div class="label">重复频率</div>
            <input class="input" v-model="form.freq" :class="{'invalid': invalidFields.includes('freq')}" placeholder="如 DAILY/WEEKLY/MONTHLY" />
          </div>
          <div class="col">
            <div class="label">重复间隔</div>
            <input class="input" v-model="form.intervalue" :class="{'invalid': invalidFields.includes('intervalue')}" type="number" min="1" placeholder="请输入间隔" />
          </div>
        </div>
        <div class="remind-end-row">
          <span class="label">结束提醒时间：</span>
          <span class="value green" :class="{'invalid': invalidFields.includes('until')}" @click="openPicker('until')">{{ form.until || '请选择' }}</span>
        </div>
      </div>
      <button class="submit-btn" type="submit" @click="onSubmit">确认添加</button>
    </form>

    <!-- 自定义年月日时分弹框 -->
    <div v-if="pickerVisible" class="custom-picker-mask" @click.self="closePicker">
      <div class="custom-picker-dialog">
        <div class="custom-picker-header">
          <span class="picker-cancel" @click="closePicker">取消</span>
          <span class="picker-title">{{ pickerTitle }}</span>
          <span class="picker-confirm" @click="confirmPicker">确认</span>
        </div>
        <div class="custom-picker-body center-content">
          <div class="picker-wheel">
            <div class="picker-col">
              <div v-for="y in yearOptions" :key="y" :class="['picker-item', pickerYear === y ? 'selected' : '']" @click="pickerYear = y">{{ y }}</div>
            </div>
            <div class="picker-col">
              <div v-for="m in monthOptions" :key="m" :class="['picker-item', pickerMonth === m ? 'selected' : '']" @click="pickerMonth = m">{{ m.toString().padStart(2, '0') }}</div>
            </div>
            <div class="picker-col">
              <div v-for="d in dayOptions" :key="d" :class="['picker-item', pickerDay === d ? 'selected' : '']" @click="pickerDay = d">{{ d.toString().padStart(2, '0') }}</div>
            </div>
            <div class="picker-col">
              <div v-for="h in hourOptions" :key="h" :class="['picker-item', pickerHour === h ? 'selected' : '']" @click="pickerHour = h">{{ h.toString().padStart(2, '0') }}</div>
            </div>
            <div class="picker-col">
              <div v-for="min in minuteOptions" :key="min" :class="['picker-item', pickerMinute === min ? 'selected' : '']" @click="pickerMinute = min">{{ min.toString().padStart(2, '0') }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { addYytxData } from '@/https/HomeHTTP'
import { useMemberStore } from '@/store'
const memberStore = useMemberStore()
const form = ref({
  medname: '',
  dtstatr: '',
  dtend: '',
  dose: '',
  units: '',
  freq: '',
  until: '',
  intervalue: '',
})
const invalidFields = ref<string[]>([])
const pickerVisible = ref(false)
const pickerType = ref<'dtstatr'|'dtend'|'until'>('dtstatr')
const pickerTitle = computed(() => {
  if (pickerType.value === 'dtstatr') return '选择用药开始时间'
  if (pickerType.value === 'dtend') return '选择用药结束时间'
  return '选择结束提醒时间'
})

const now = new Date()
const thisYear = now.getFullYear()
const thisMonth = now.getMonth() + 1
const thisDay = now.getDate()
const thisHour = now.getHours()
const thisMinute = now.getMinutes()

const pickerYear = ref(thisYear)
const pickerMonth = ref(thisMonth)
const pickerDay = ref(thisDay)
const pickerHour = ref(thisHour)
const pickerMinute = ref(thisMinute)

const yearOptions = computed(() => {
  const nowYear = thisYear
  return Array.from({length: 11}, (_, i) => nowYear + i)
})
const monthOptions = computed(() => {
  if (pickerYear.value === thisYear) {
    return Array.from({length: 12 - thisMonth + 1}, (_, i) => thisMonth + i)
  }
  return Array.from({length: 12}, (_, i) => i + 1)
})
const dayOptions = computed(() => {
  const daysInMonth = new Date(pickerYear.value, pickerMonth.value, 0).getDate()
  let startDay = 1
  if (pickerYear.value === thisYear && pickerMonth.value === thisMonth) {
    startDay = thisDay
  }
  return Array.from({length: daysInMonth - startDay + 1}, (_, i) => startDay + i)
})
const hourOptions = computed(() => {
  if (
    pickerYear.value === thisYear &&
    pickerMonth.value === thisMonth &&
    pickerDay.value === thisDay
  ) {
    return Array.from({length: 24 - thisHour}, (_, i) => thisHour + i)
  }
  return Array.from({length: 24}, (_, i) => i)
})
const minuteOptions = computed(() => {
  if (
    pickerYear.value === thisYear &&
    pickerMonth.value === thisMonth &&
    pickerDay.value === thisDay &&
    pickerHour.value === thisHour
  ) {
    return Array.from({length: 60 - thisMinute}, (_, i) => thisMinute + i)
  }
  return Array.from({length: 60}, (_, i) => i)
})

function openPicker(type: 'dtstatr'|'dtend'|'until') {
  pickerType.value = type
  let date = new Date()
  if (form.value[type]) {
    date = new Date(form.value[type])
  }
  pickerYear.value = date.getFullYear()
  pickerMonth.value = date.getMonth() + 1
  pickerDay.value = date.getDate()
  pickerHour.value = date.getHours()
  pickerMinute.value = date.getMinutes()
  pickerVisible.value = true
}
function closePicker() {
  pickerVisible.value = false
}
function confirmPicker() {
  const date = new Date(
    pickerYear.value,
    pickerMonth.value - 1,
    pickerDay.value,
    pickerHour.value,
    pickerMinute.value
  )
  const formatted = formatDateTime(date)
  if (pickerType.value === 'dtstatr') form.value.dtstatr = formatted
  if (pickerType.value === 'dtend') form.value.dtend = formatted
  if (pickerType.value === 'until') form.value.until = formatted
  pickerVisible.value = false
}
function formatDateTime(date: Date | string) {
  if (!date) return ''
  const d = new Date(date)
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const h = String(d.getHours()).padStart(2, '0')
  const min = String(d.getMinutes()).padStart(2, '0')
  return `${y}-${m}-${day} ${h}:${min}`
}
const onSubmit = async () => {
  console.log(form.value)
  invalidFields.value = []
  const required = ['medname','dtstatr','dtend','dose','units','freq','until','intervalue']
  required.forEach(key => {
    if (!form.value[key] || (typeof form.value[key] === 'string' && !form.value[key].trim())) {
      invalidFields.value.push(key)
    }
  })
  if (invalidFields.value.length > 0) return
  const params = { ...form.value }
  // console.log(params)
  const res = await addYytxData(params)
  console.log(res)
  if (res.code === 200) {
    uni.navigateTo({
      url: '/pages/component/yytx/yytx',
    })
  } else {
    uni.showToast({
      title: res.msg,
      icon: 'none',
    })
  }
}
// 联动刷新下级选项
watch([pickerYear, pickerMonth], () => {
  if (!dayOptions.value.includes(pickerDay.value)) {
    pickerDay.value = dayOptions.value[0]
  }
})
watch([pickerYear, pickerMonth, pickerDay], () => {
  if (!hourOptions.value.includes(pickerHour.value)) {
    pickerHour.value = hourOptions.value[0]
  }
})
watch([pickerYear, pickerMonth, pickerDay, pickerHour], () => {
  if (!minuteOptions.value.includes(pickerMinute.value)) {
    pickerMinute.value = minuteOptions.value[0]
  }
})
</script>

<style scoped lang="scss">
.remind-page {
  background: #fff;
  min-height: 100vh;
  padding: 0 0 32px 0;
  .section {
    margin: 24px 24px 0 24px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    padding: 18px 18px 8px 18px;
    .section-title {
      color: #19c37c;
      font-weight: bold;
      font-size: 17px;
      margin-bottom: 12px;
      border-left: 4px solid #19c37c;
      padding-left: 8px;
    }
    .form-group {
      margin-bottom: 18px;
      .label {
        font-size: 15px;
        color: #222;
        font-weight: bold;
        margin-bottom: 4px;
      }
      .input {
        width: 100%;
        border: none;
        border-bottom: 1.5px solid #19c37c;
        font-size: 16px;
        padding: 8px 0;
        background: transparent;
        color: #aaa;
        &.invalid {
          border-bottom-color: #ff6b6b;
          color: #ff6b6b;
        }
      }
      select {
        width: 100%;
        border: none;
        border-bottom: 1.5px solid #19c37c;
        font-size: 16px;
        padding: 8px 0;
        background: transparent;
        color: #aaa;
        &.invalid {
          border-bottom-color: #ff6b6b;
          color: #ff6b6b;
        }
      }
    }
    .row {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      margin-bottom: 18px;
      .col {
        flex: 1;
        text-align: left;
        .label {
          font-size: 15px;
          color: #222;
          font-weight: bold;
          margin-bottom: 4px;
        }
        .value {
          font-size: 18px;
          font-weight: bold;
          color: #222;
          &.green {
            color: #19c37c;
          }
          cursor: pointer;
          &.invalid {
            color: #ff6b6b;
          }
        }
      }
      .col + .col {
        margin-left: 24px;
      }
    }
    .remind-end-row {
      display: flex;
      align-items: center;
      font-size: 16px;
      color: #222;
      margin-top: 8px;
      .label {
        font-size: 16px;
        color: #222;
        font-weight: bold;
      }
      .value {
        color: #19c37c;
        font-size: 18px;
        font-weight: bold;
        margin-left: 8px;
        cursor: pointer;
        &.invalid {
          color: #ff6b6b;
        }
      }
    }
  }
  .submit-btn {
    width: 92%;
    margin: 32px auto 0 auto;
    display: block;
    background: #19c37c;
    color: #fff;
    font-size: 20px;
    font-weight: bold;
    border: none;
    border-radius: 12px;
    padding: 14px 0;
    box-shadow: 0 2px 8px rgba(25, 195, 124, 0.1);
    cursor: pointer;
    transition: background 0.2s;
    &:active {
      background: #13a06b;
    }
  }
}
.custom-picker-mask {
  position: fixed; left: 0; right: 0; top: 0; bottom: 0;
  background: rgba(0,0,0,0.08);
  z-index: 1000;
  display: flex; align-items: center; justify-content: center;
}
.custom-picker-dialog {
  background: #fff;
  border-radius: 16px;
  width: 480px;
  box-shadow: 0 2px 16px rgba(0,0,0,0.08);
  overflow: hidden;
}
.custom-picker-header {
  display: flex; justify-content: space-between; align-items: center;
  padding: 16px 18px 8px 18px;
  font-size: 17px; font-weight: bold; color: #222;
  .picker-cancel, .picker-confirm { color: #8c8c8c; font-size: 15px; cursor: pointer; }
  .picker-title { flex: 1; text-align: center; color: #222; }
}
.custom-picker-body {
  display: flex; justify-content: center; align-items: center; padding: 18px 0 18px 0;
  height: 220px;
  .picker-wheel {
    display: flex; border-radius: 12px; background: #fff; padding: 8px 0;
    .picker-col {
      margin: 0 18px; min-width: 56px;
      display: flex;
      flex-direction: column;
      align-items: center;
      max-height: 180px;
      overflow-y: auto;
      /* 隐藏滚动条 */
      scrollbar-width: none; /* Firefox */
      -ms-overflow-style: none; /* IE 10+ */
    }
    .picker-col::-webkit-scrollbar {
      display: none; /* Chrome/Safari/Webkit */
    }
    .picker-item {
      font-size: 20px; color: #bbb; padding: 4px 0; cursor: pointer; text-align: center;
      &.selected { color: #222; font-weight: bold; background: #f5f5f5; border-radius: 6px; }
    }
  }
}
.custom-picker-body.center-content {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>